#
# pecplotnb.py - Defines main program frame, with an AUI notebook
# for each plot
#

import wx
import wx.aui
import sys, argparse, os 
from PecPanel import TreePlotPanel
from dialogs import SettingsDlg, SizeDialog
import numpy as np


ID_NEW = wx.NewId()
ID_QUIT = wx.NewId()
ID_ADD = wx.NewId()
ID_SAVEC = wx.NewId()
ID_SAVEF = wx.NewId()
ID_SETTINGS = wx.NewId()


class PecPlotFrame(wx.Frame):
    def __init__(self, filename, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.notebook_panes = []
        self.trees = []        
        self.current_nb = 0        
                    
        # If no file has been given at command line, prompt the user for input
        if filename == '':
            while filename == '':        
                filename = self.NewPlot()
                if filename == '':
                    mdlg = wx.MessageDialog(self, 'No Input File Given.  Try Again?', 'File Not Found', wx.YES_NO)
                    if mdlg.ShowModal() == wx.ID_YES:
                        pass
                    else:
                        sys.exit(0)
                    mdlg.Destroy() 

        self.notebook = wx.aui.AuiNotebook(self, wx.ID_ANY)
        self.notebook_panes.append(TreePlotPanel(self.notebook, filename))    
        self.current = self.notebook_panes[self.current_nb]   
        
        self.init_menu()        
        self.notebook.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnChange)
        self.__do_layout()
        self.Maximize()
        
    def NewPlot(self):
        inputfile = ''
        
        wdir = os.getcwd()        
        choices = ['Use Plot %d Data' % pn for pn in range(1,len(self.notebook_panes)+1) ]
        choices.append('Use Existing Input File')
        choices.append('Create New Input File')
        dlg = wx.SingleChoiceDialog(
                self, 'Input Options', 'PecPlot',
                choices, 
                wx.CHOICEDLG_STYLE
                )
        wildcard = "PecPlot Input File (*.pec)|*.pec|" \
           "All Files (*.*)|*.*"        
    
        if dlg.ShowModal() == wx.ID_OK:
            choice = dlg.GetSelection()
            if choice == (len(choices) - 2):
                fdlg = wx.FileDialog(dlg, message="Choose a file",
                defaultDir=wdir, 
                defaultFile="",
                wildcard=wildcard,
                style=wx.OPEN )
                
                if fdlg.ShowModal() == wx.ID_OK:
                    inputfile = fdlg.GetPath()
                fdlg.Destroy()
            elif choice == (len(choices) - 1):
                sdlg = SettingsDlg(self, None, None, -1, "Plot Setup")
                if sdlg.ShowModal() == wx.ID_OK:

                    fdlg = wx.FileDialog(dlg, message="Choose a file",
                    defaultDir=wdir, 
                    defaultFile="",
                    wildcard=wildcard,
                    style=wx.SAVE )
                    
                    if fdlg.ShowModal() == wx.ID_OK:
                        inputfile = fdlg.GetPath()
                    fdlg.Destroy()
                    sdlg.writeFile(inputfile)
                sdlg.Destroy()
            else:
                inputfile = self.notebook_panes[choice].configfile
        
        dlg.Destroy()
        os.chdir(wdir)
        return inputfile
        
      
    def init_menu(self):
        self.menubar = wx.MenuBar()
        self.fileMenu = wx.Menu()
        item1 = self.fileMenu.Append(ID_NEW, 'New', 'Opens a new tab')
        item2 = self.fileMenu.Append(ID_SAVEC, 'Save Config', 'Save current configuration')                
        item3 = self.fileMenu.Append(ID_SAVEF, 'Save Figure', 'Save current plot')         
        item4 = self.fileMenu.Append(ID_SETTINGS, 'Plot Settings', 'Molecule/Window/File Settings') 
        item5 = self.fileMenu.Append(ID_QUIT, 'Quit', 'Quit application')
        self.menubar.Append(self.fileMenu, "File")
        self.SetMenuBar(self.menubar)


    def __do_layout(self):
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        plotnumber = self.current_nb + 1
        self.notebook.AddPage(self.notebook_panes[0], "Plot %d" % plotnumber)
        self.sizer.Add(self.notebook, 1, wx.EXPAND, 0)
        self.SetSizer(self.sizer)
        self.sizer.Fit(self)
        self.Layout()
    
       
    def OnChange(self, event):
        try:
            self.current = self.notebook_panes[event.selection]
        except AttributeError:
            pass
                
    def OnSettings(self, event):        
        fc = {'fstring': self.current.fstring, 
              'units': self.current.states[-1].units,
              'states': self.current.states}
        currents = {'mol': self.current.name, 'ax': self.current.plotpanel.axprops,
                    'win': self.current.plotpanel.vprops, 'styles': self.current.styles,
                    'files': fc}
        units = {'input' : self.current.states[-1].units, 'output': self.current.units}
        dlg = SettingsDlg(self, currents, units, -1, "Plot Setup")
        
        
        if dlg.ShowModal() == wx.ID_OK:
            changes = dlg.getOutput()
       
            self.current.plotpanel.resetWin(changes[2])
            self.current.plotpanel.resetAxes(changes[1])
            self.current.plotpanel.updateWindow()
            #self.current.resetUnits(changes[3])
            
            self.current.fstring = changes[4]
            datafiles = {}
            for fileinfo in changes[5]:
                line = ''
                for item in fileinfo[1:-1]:
                    line += item + ", "
                line += str(fileinfo[-1])
                datafiles[fileinfo[0]] = line.split(", ")
            #self.current.setStates(datafiles)
            #changes[6] = stylesdict    
            self.current.resetPlot(datafiles, changes[3])
        dlg.Destroy()
        return
             
    def OnNew(self, event):
        
        inputfile = self.NewPlot()
        if inputfile == '':
            mdlg = wx.MessageBox('No Input File Given')
            return
                
        self.notebook_panes.append(TreePlotPanel(self.notebook, inputfile))
        pagenumber = len(self.notebook_panes)
        self.notebook.AddPage(self.notebook_panes[pagenumber-1], "Plot %d" % pagenumber, select = False)
        self.notebook.SetSelection(pagenumber-1)
        
    def OnSaveConfig(self, event):
        filename = ''
        wildcard = "PecPlot Input File (*.pec)|*.pec|" \
                   "All Files (*.*)|*.*"
        fdlg = wx.FileDialog(self, message="Choose a file",
                             defaultDir=os.getcwd(), 
                             defaultFile="",
                             wildcard=wildcard,
                             style=wx.SAVE )
        
        if fdlg.ShowModal() == wx.ID_OK:
            filename = fdlg.GetPath()
        fdlg.Destroy()
        try:        
            self.current.write_config_file(filename) 
        except IOError:
            wx.MessageBox("Sorry! Unable to save")
        
    def OnQuit(self,event):
        self.Close(True)
        
        
    def OnSaveFig(self, event):
        filename = ''
        wildcard = "PDF (*.pdf)|*.pdf|" \
                   "All Files (*.*)|*.*"
        axprops = self.current.axprops
        vprops = self.current.vprops
        Fig = self.current.Fig
        ax = self.current.ax
        oldsize = Fig.get_size_inches()
    
        ax.set_xlim(axprops['xmin'], axprops['xmax'])
        ax.set_xticks( np.arange(axprops['xmin'], axprops['xmax'], axprops['xticks']) )
        ax.set_ylim(axprops['ymin'], axprops['ymax'])        
        ax.set_yticks( np.arange(axprops['ymin'],axprops['ymax'],axprops['yticks']) )
        dlg = SizeDialog(self, Fig)
        if dlg.ShowModal() == wx.ID_OK:
            out = dlg.getOutput()
            Fig.set_size_inches(out['Width'], out['Height'])
            fdlg = wx.FileDialog(self, message="Choose a file",
                             defaultDir=os.getcwd(), 
                             defaultFile="",
                             wildcard=wildcard,
                             style=wx.SAVE )
            if fdlg.ShowModal() == wx.ID_OK:
                filename = fdlg.GetPath()
                Fig.savefig(filename)
            Fig.set_size_inches(oldsize)
        fdlg.Destroy()
        dlg.Destroy()
        ax.set_xlim(vprops['xmin'], vprops['xmax'])
        ax.set_xticks( np.arange(vprops['xmin'], vprops['xmax'], axprops['xticks']) )
        ax.set_ylim(vprops['ymin'], vprops['ymax'])        
        ax.set_yticks( np.arange(vprops['ymin'],vprops['ymax'],vprops['yticks']) )


                           


# end of class MyFrame
if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    parser = argparse.ArgumentParser(description='PecPlot Command Line Options')
    parser.add_argument('-i','--infile', help='Input file name',required=False,default='')
    args = parser.parse_args()
    filename = args.infile 
    frame = PecPlotFrame(filename, None, wx.ID_ANY, "PecPlot")
    app.SetTopWindow(frame)
    frame.Show()

    frame.Connect(ID_NEW, -1, wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnNew)
    frame.Connect(ID_QUIT, -1, wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnQuit)
    frame.Connect(ID_SAVEC, -1, wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnSaveConfig)
    frame.Connect(ID_SETTINGS, -1, wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnSettings)
    frame.Connect(ID_SAVEF, -1, wx.wxEVT_COMMAND_MENU_SELECTED, frame.OnSaveFig)
   # wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()
